package cn.lwj.bak;

import cn.lwj.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//日志输出类
@Slf4j
//表示这是一个过滤器类
//@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*") // /*表示拦截所有servlet请求
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        log.info("拦截到请求：" + request.getRequestURI());
//        log.info("拦截到请求：{}",request.getRequestURI());
        String requestURI = request.getRequestURI();
        if( requestURI.contains("login") || requestURI.contains("Login") || requestURI.contains("logout")){
            log.info("该请求无需处理");
            filterChain.doFilter(request,response); // 放行给下一个过滤器 否则就会卡在这个过滤器不在执行后续代码
            return;
        }
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已登录");
            filterChain.doFilter(request,response); // 放行给下一个过滤器 否则就会卡在这个过滤器不在执行后续代码
            return;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN"))); // 配合前端实现业务
        response.sendRedirect(request.getContextPath() + "/backend/page/login/login.html");
    }
}
